<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/6/25
 * Time: 21:13
 */

namespace Home\Logic;


use Home\Model\Page;
use Think\Exception;

class WithdrawalsLogic
{
    /**
     * 用户提现
     * @param $user_id int 用户id
     * @param $log array 银行账户,银行名称，提现金额，账户名称
     * @return int 1成功 2错误 3金额不足
     */
    public function withdrawals($user_id,$log){
        $model = M();
        $model->startTrans();
        try{
            $user_money = D('Users')->where(array('user_id'=>$user_id))->getField('user_money');
            if($user_money < $log['money']){
                return 3;
            }
            $log['user_id'] = $user_id;
            $log['status'] = 0;
            $log['create_time'] = time();
            $log['remark'] = '';
            $model->table('tp_withdrawals')->add($log);
            //$model->table('tp_users')->where(array('user_id'=>$user_id))->setDec('user_money',$log['money']);
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            return 2;
        }
    }

    public function getWithdrawalsList($user_id,$pagenum,$pagesize){
        $startno = ($pagenum - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['user_id'] = ':user_id';
        $bind[':user_id'] = $user_id;
        $withdrawalsList = D('Withdrawals')
            ->where($map)->bind($bind)
//            ->limit($limit)
            ->order('id desc')
            ->limit($limit)
            ->select();
        foreach ($withdrawalsList as $key => $value){
            $withdrawalsList[$key]['create_time'] = date('Y-m-d m:s',$value['create_time']);
        }
        $data['list'] = $withdrawalsList;
        $count = D('Withdrawals')->where($map)->bind($bind)->count();
        $page = new Page($pagenum, $count, $pagesize);
        $page = (array)$page;//转换为数组
        //分页数据
//        $page['cpage'] = $pagenum;//当前页面
//        $page['totalnum'] = floor(($count + $pagesize - 1) / $pagesize);
        $data['page'] = $page;
        return $data;
    }
}